package cn.wl.pchart.domain;

import cn.wl.pchart.controller.MessageController;
import cn.wl.pchart.entity.Message;
import cn.wl.pchart.service.CommunicationService;
import cn.wl.pchart.tools.Communication;
import cn.wl.pchart.tools.Signal;
import cn.wl.pchart.tools.Tools;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

// websocket服务
@ServerEndpoint(value = "/websocket/{from}")
@Component
public class WebSocketServer {

    @Autowired
    CommunicationService communicationService;

    // 用户id
    private String id = null;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    // 用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    // 与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("from") String from) {
        this.session = session;
        System.out.println(from);
        this.setId(from);
        webSocketSet.add(this);     //加入set中
        System.out.println("有新连接加入！当前在线人数为" + webSocketSet.size());
        // this.session.getAsyncRemote().sendText("恭喜您成功连接上WebSocket-->当前在线人数为：" + webSocketSet.size());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "WebSocket 连接成功！");
        this.session.getAsyncRemote().sendText(jsonObject.toString());
        // this.session.getAsyncRemote().sendText(Tools.aesEncrypt(jsonObject.toString()));
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        System.out.println("有一连接关闭！当前在线人数为" + webSocketSet.size());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);

        message = message.replaceAll("\\[add\\]", "+");

        JSONObject json = null;
        Signal signal = Communication.getJsonFromMessage(message);
        System.out.println("Signal:" + "code=" + signal.code + "&msg=" + signal.msg);
        if (signal.data != null) {
            System.out.println("Data: " + signal.data.toString());
        }
        if (signal.code.equals(0)) {
            json = signal.data;
        }

        JSONObject result = new JSONObject();

        if (json != null) {

            System.out.println("来自客户端的消息:" + json);

            WebSocketServer connect = findConnect(json.getString("to"));

            result.put("from", json.getString("from"));
            result.put("to", json.getString("to"));
            result.put("data", json.getString("data"));
            result.put("time", "null");
            result.put("mid", "null");

            if (connect != null) {
                String sendMessage = result.toString();
                // 加密
                sendMessage = Tools.aesEncrypt(sendMessage);
                // 将+转义成[add]
                sendMessage = sendMessage.replaceAll("\\\\+", "[add]");
                // 发送消息到指定用户
                connect.session.getAsyncRemote().sendText(sendMessage);
                System.out.println(json.getString("from") + "给" + json.getString("to") + "发送的消息：" + Tools.aesDecrypt(sendMessage));
            }

        }


    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    // 查找一个对应id的连接
    public WebSocketServer findConnect(String id) {
        for (WebSocketServer i : webSocketSet) {
            if (i != null) {
                if (i.getId().equals(id)) {
                    return i;
                }
            }
        }
        return null;
    }

}